// src/main/resources/static/js/knife4j-encrypt-plugin.js
(function() {
    // AES加密函数
    function encryptData(data, secretKey) {
        const iv = CryptoJS.lib.WordArray.random(16);
        const encrypted = CryptoJS.AES.encrypt(
            data,
            CryptoJS.enc.Utf8.parse(secretKey),
            {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            }
        );
        return iv.toString(CryptoJS.enc.Base64) + "|" + encrypted.ciphertext.toString(CryptoJS.enc.Base64);
    }

    // 定义Knife4j拦截器
    const interceptor = {
        name: 'encryptInterceptor',
        request: function(request) {
            // 从localStorage或配置中获取密钥（生产环境需改进）
            const secretKey = localStorage.getItem('aesSecretKey') || '0123456789abcdef0123456789abcdef';

            // 只对特定路径加密（根据实际API调整）
            if (request.url && request.url.endsWith('/api/execute-sql')) {
                try {
                    // 加密请求体中的敏感字段
                    if (request.body) {
                        // 处理JSON对象格式
                        if (typeof request.body === 'object') {
                            if (request.body.sqlCode) {
                                request.body.sqlCode = encryptData(request.body.sqlCode, secretKey);
                            }
                        }
                        // 处理JSON字符串格式
                        else if (typeof request.body === 'string') {
                            try {
                                const bodyObj = JSON.parse(request.body);
                                if (bodyObj.sqlCode) {
                                    bodyObj.sqlCode = encryptData(bodyObj.sqlCode, secretKey);
                                    request.body = JSON.stringify(bodyObj);
                                }
                            } catch (e) {
                                console.log('非JSON格式请求体，跳过加密', e);
                            }
                        }
                    }
                } catch (error) {
                    console.error('加密过程出错:', error);
                }
            }

            return request;
        }
    };

    // 注册拦截器
    if (window.Knife4j) {
        window.Knife4j.addInterceptor(interceptor);
    } else {
        console.error('Knife4j未加载，加密插件注册失败');
    }
})();